<template>
  <div>
    <a-modal
      title="批量更换用工单位"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      :destroyOnClose="true"
    >
      <a-form :form="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="原用工单位">
          <a-input :disabled="true" v-model="companyName" />
        </a-form-item>
        <a-form-item label="新用工单位">
          <a-select
            show-search
            option-filter-prop="children"
            allowClear
            :filter-option="filterOption"
            style="width: 100%"
            v-decorator="['companyId', { rules: [{ required: true, message: '请选择新用工单位' }] }]"
          >
            <a-select-option :value="i.id" v-for="i in options" :key="i.id">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="!isJF" label="工作性质">
          <a-select
            style="width: 100%"
            @change="postTypeChange"
            v-decorator="['postType', { rules: [{ required: true, message: '请选择工作性质' }] }]"
          >
            <a-select-option :value="i.value" v-for="i in postTypeOptions" :key="i.value">{{ i.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="原用工单位离职日期">
          <a-date-picker
            @change="onChangeDatepreQuitDate"
            style="width: 100%"
            v-decorator="['preQuitDate', { rules: [{ required: true, message: '请选择原用工单位离职日期' }] }]"
          />
        </a-form-item>
        <a-form-item label="新用工单位入职日期">
          <a-date-picker
            style="width: 100%"
            @change="onChangeDate"
            v-decorator="['JoinDate', { rules: [{ required: true, message: '请选择新用工单位入职日期' }] }]"
          />
        </a-form-item>
        <div v-if="postTypeShow">
          <a-form-item label="员工状态">
            <a-select
              style="width: 100%"
              @change="handleChange"
              v-decorator="['formalType', { rules: [{ required: true, message: '请选择员工状态' }] }]"
            >
              <a-select-option :value="i.value" v-for="i in formalTypeOptions" :key="i.value">{{ i.label }}</a-select-option>
            </a-select>
          </a-form-item>
          <div v-if="probationDays">
            <a-form-item label="试用期">
              <a-input-number
                v-decorator="[
                  'probationDays',
                  {
                    rules: [{ required: true, message: '请填写试用期' }]
                  }
                ]"
                style="width: 100%"
                :min="0"
                :formatter="(value) => `${value}天`"
                placeholder="试用期天数"
                @change="probationDaysChange"
              />
            </a-form-item>
            <a-form-item label="预计转正日期">
              <a-date-picker v-decorator="['turnStraightDate']" style="width: 100%" type="date" placeholder="请选择" disabled />
            </a-form-item>
          </div>
          <a-form-item label="预计转正日期" v-if="probationDays === false">
            <a-date-picker
              v-decorator="[
                'turnStraightDate',
                {
                  rules: [{ required: true, message: '请填写转正日期' }]
                }
              ]"
              style="width: 100%"
              type="date"
              placeholder="请选择"
            />
          </a-form-item>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import moment from "moment";
import { afterTime } from "@/utils/index";
import { mapState, mapGetters } from "vuex";
export default {
  data() {
    return {
      companyName: this.$store.state.hr.companyName,
      companyId: this.$store.state.hr.companyId,
      postTypeShow: true,
      options: [],
      probationDays: null,
      selectedRows: [],
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this, { name: "coordinated" }),
      formalTypeOptions: [
        { value: 1, label: "试用" },
        { value: 2, label: "正式" }
      ]
    };
  },
  computed: {
    ...mapGetters(["isJF"]),
    ...mapState(["hr"]),
    companyList() {
      return this.hr.companyList;
    },
    postTypeOptions() {
      return this.$store.state.enums.postTypeLst;
    }
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    probationDaysChange(value) {
      // 试用天数
      if (this.form.getFieldValue("JoinDate")) {
        const newTime = afterTime(this.form.getFieldValue("JoinDate"), value);
        setTimeout(() => {
          this.form.setFieldsValue({
            turnStraightDate: this.moment(newTime, "YYYY-MM-DD")
          });
        }, 300);
      }
    },
    tabData(dateString1, dateString2) {
      var startDate = Date.parse(dateString1);
      var endDate = Date.parse(dateString2);
      if (startDate > endDate) {
        return 0;
      }
      if (startDate === endDate) {
        return 0;
      }
      var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
      return days;
    },
    onChangeDatepreQuitDate(date, dateString) {
      const JoinDate = this.form.getFieldValue("JoinDate");
      if (JoinDate) {
        const data = this.tabData(JoinDate, moment(dateString).format("YYYY-MM-DD"));
        if (data !== 0) {
          this.$message.error("新用工单位入职日期应该大于等于原用工单位离职日期");
          setTimeout(() => {
            this.form.setFieldsValue({
              preQuitDate: null
            });
          });
          return;
        }
      }
    },
    onChangeDate(date, dateString) {
      // console.log(date, dateString);
      // 入职日期
      const preQuitDate = this.form.getFieldValue("preQuitDate");
      if (preQuitDate) {
        const data = this.tabData(dateString, moment(preQuitDate).format("YYYY-MM-DD"));
        if (data !== 0) {
          this.$message.error("新用工单位入职日期应该大于等于原用工单位离职日期");
          setTimeout(() => {
            this.form.setFieldsValue({
              JoinDate: null
            });
          });
          return;
        }
      }
      const probationDay = this.form.getFieldValue("probationDays");
      if (probationDay && dateString) {
        const newTime = afterTime(dateString, probationDay);
        setTimeout(() => {
          this.form.setFieldsValue({
            turnStraightDate: this.moment(newTime, "YYYY-MM-DD")
          });
        }, 300);
      }
    },
    postTypeChange(val) {
      console.log(val);
      if (val === 2 || val === 3) {
        this.postTypeShow = false;
      } else {
        this.postTypeShow = true;
      }
      console.log(" this.postTypeShow", this.postTypeShow);
    },
    handleChange(value) {
      // 员工状态
      if (value === 1) {
        this.probationDays = true;
      } else {
        this.probationDays = false;
        if (this.form.getFieldValue("JoinDate")) {
          setTimeout(() => {
            this.form.setFieldsValue({
              turnStraightDate: this.form.getFieldValue("JoinDate")
            });
          }, 300);
        }
      }
    },
    showModal(e) {
      // console.log("companyName", e);
      this.selectedRows = e;
      this.visible = true;
      this.getCompanyId();
    },
    getCompanyId() {
      this.options = JSON.parse(JSON.stringify(this.companyList));
      this.options.forEach((element, index) => {
        if (element.id === this.$store.state.hr.companyId) {
          this.options.splice(index, 1);
        }
      });
    },
    handleOk(e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          values.JoinDate = values.JoinDate.format("YYYY-MM-DD");
          // values.preQuitDate = values.preQuitDate.format("YYYY-MM-DD");
          values.turnStraightDate = values.turnStraightDate ? values.turnStraightDate.format("YYYY-MM-DD") : null;
          if (values.postType === 2 || values.postType === 3) {
            values.formalType = 2;
            values.turnStraightDate = moment().format("YYYY-MM-DD");
          }
          const data = {
            preQuitDate: values.preQuitDate.format("YYYY-MM-DD"),
            companyId: this.$store.state.hr.companyId,
            currentCompanyId: values.companyId,
            currentFormalType: values.formalType,
            currentJoinDate: values.JoinDate,
            currentPostType: values.postType,
            currentPreJoinDate: values.turnStraightDate,
            currentProbationDays: values.probationDays,
            currentStatus: this.selectedRows[0].status === 1 ? 1 : 2,
            currentTurnStraightDate: values.turnStraightDate,
            empInformationList: this.selectedRows.map((z) => {
              return {
                empId: z.id,
                name: z.name
              };
            })
          };
          // console.log(data);
          this.confirmLoading = true;
          this.$request({
            method: "put",
            url: `/hr/api/v1/empInfos/empBatchChangeCompanyId`,
            data: data
          })
            .then((res) => {
              this.visible = false;
              this.confirmLoading = false;
              this.$message.success(res.msg);
              this.$emit("saveOK");
            })
            .catch((err) => {
              this.confirmLoading = false;
              console.log("debug log --> ", err);
            });
        }
      });
    },
    handleCancel(e) {
      this.visible = false;
    }
  }
};
</script>
